from werkzeug.exceptions import abort
from werkzeug.local import LocalProxy
from flask import request
from flask_login import current_user
from mongoengine import Document as MongoDocument
from elasticsearch_dsl import Document as EsDocument


def get_object_or_404(model, **kwargs):
    '''
        1.mongoengine 中找不到对应的内容
        2.es中找不到对应的内容
    '''
    try:
        if issubclass(model, MongoDocument):
            return model.objects.get(**kwargs)
        elif issubclass(model, EsDocument):
            return model.get(**kwargs)
    except Exception as e:
        clist = ['%s=%s' % (item[0], item[1]) for item in kwargs.items()]
        errmsg = 'can not find %s - %s' % (model.__name__, ';'.join(clist))
        abort(404, errmsg)


def get_ori_object_or_404(model, **kwargs):
    '''
        1.mongoengine 中找不到对应的内容
        2.es中找不到对应的内容
    '''
    try:
        if issubclass(model, MongoDocument):
            return model.ori_objects.get(**kwargs)
        elif issubclass(model, EsDocument):
            return model.get(**kwargs)
    except Exception as e:
        clist = ['%s=%s' % (item[0], item[1]) for item in kwargs.items()]
        errmsg = 'can not find %s - %s' % (model.__name__, ';'.join(clist))
        abort(404, errmsg)


def get_pagination_arguments(page=('page', 1), page_size=('page_size', 20), order_fields=None):
    from flask_restplus import reqparse

    pagination_arguments = reqparse.RequestParser()
    pagination_arguments.add_argument(page[0], type=int, required=False, default=page[1], help='页码')
    pagination_arguments.add_argument(page_size[0], type=int, required=False, default=page_size[1], help='页长')
    if order_fields is not None:
        pagination_arguments.add_argument(order_fields[0], type=str, required=False, default=order_fields[1], help='排序')
    return pagination_arguments


pagination = get_pagination_arguments()


def _get_company():
    from app.enterprise.models import EnterPrise
    cid = request.headers.get('EnterPrise-id') or request.args.get('_enterprise_id_') or EnterPrise.base_company
    return EnterPrise.objects.get(name=cid)


current_company = LocalProxy(lambda: _get_company())


def _get_company_id():
    from app.conf import RUN_CONFIG
    if RUN_CONFIG.RUNNING_ENTERPRISE:
        return RUN_CONFIG.RUNNING_ENTERPRISE
    from app.enterprise.models import EnterPrise
    if hasattr(current_user, '_enterprise_id_') and current_user._enterprise_id_:
        return current_user._enterprise_id_
    return current_user.enterprise_id if current_user and not current_user.is_anonymous else EnterPrise.base_company


current_enterprise_id = LocalProxy(lambda: _get_company_id())


avg = lambda l: sum(l) / len(l)
